package com.gege;

import java.util.concurrent.*;

/**
 * @author gechenpeng
 * @date 2021-04-12
 */
public class Demo2 {

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = new ThreadPoolExecutor(5, 5,
                1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1024),
                new ThreadPoolExecutor.CallerRunsPolicy());

        // 创建 FutureTask
        FutureTask<String> futureTask = new FutureTask<>(() -> execute());

        long start = System.currentTimeMillis();

        // 将 FutureTask 直接交给 ExecutorService 执行
        executorService.execute(futureTask);

        executorService.shutdown();

        // 通过执行 FutureTask.get() 方法来等待任务执行完成
        String message = futureTask.get();

        System.out.println("线程运行的结果是: " + message + ", 耗时: " +
                (System.currentTimeMillis() - start) + " ms");
    }

    private static String execute() throws Exception {
        Thread.sleep(5000);
        return "ok";
    }
}
